package viper

import (
	"fmt"
	myzap "hardware_test/utils/zap"
	"os"
	"path/filepath"

	"github.com/spf13/viper"
)

type CfgPoint struct {
	Type string
	Key  string
	Val  any
}

var (
	VP *viper.Viper
)

func InitViper() *viper.Viper {
	rootPath, err := os.Executable()
	if err != nil {
		myzap.Logger.Panic("Init failed")
	}
	rootPath = filepath.Dir(rootPath)
	fmt.Printf("rootPath: %s\r\n", rootPath)
	path := filepath.Join(rootPath, "config.json")
	fmt.Printf("Path: %s\r\n", path)
	VP = viper.New()
	VP.SetConfigFile(path)
	VP.SetConfigType("json")
	err = VP.ReadInConfig()
	if err != nil {
		myzap.Logger.Panic("Init failed, ", path)
		fmt.Println("Read config file error!")
	}
	VP.Set("root_path", rootPath)
	VP.MergeInConfig()
	return VP
}

func CfgSet(cfgs ...*CfgPoint) error {
	var cfgstr string
	for _, cfg := range cfgs {
		cfgstr = cfg.Type + "." + cfg.Key
		VP.Set(cfgstr, cfg.Val)
	}
	return nil
}

func CfgSave() error {
	err := VP.WriteConfig()
	if err != nil {
		return err
	}
	return nil
}
